package com.Education.Controller;

import com.Education.config.JwtToken;
import com.Education.pojo.Course;
import com.Education.pojo.Schedule;
import com.Education.pojo.User;
import com.Education.server.ScheduleService;
import com.Education.server.UserService;
import com.Education.util.HttpObtainSchedule;
import com.Education.util.JwtUtils;
import com.Education.util.ResponseUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.Education.util.HttpObtainSchedule.jsonToMap;

@RestController
@RequestMapping("/wx")
public class ScheduleController {

    private final Log logger = LogFactory.getLog(ScheduleController.class);

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserService userService;
    @Autowired
    ScheduleService scheduleService;

    @GetMapping("/getSchedule")
    public Object getSchedule(HttpServletRequest req, String grade, String semester) throws IOException {

        logger.info("============>>到了getSchedule");

        String token = req.getHeader("Authorization");
        //System.out.println("isSchedule=====Authorization："+token);
        String username = jwtUtils.getClaimByToken((String) new JwtToken(token).getPrincipal()).getSubject();

        String id = username+grade+semester;

        User user = userService.getUserByName(username);


        //将要返回的课程列表
        List<Course> courseList;

        //从数据库获取
        Schedule schedule = scheduleService.querySchedule(id);
        if(schedule != null){
            Map<String, Object> result = schedule.getScheduleMap();
            String  param= JSON.toJSONString(result);   //map转json,不转后面的会报json格式错误

            Map<String, Object> result2 = jsonToMap(param); //再处理json

            courseList = HttpObtainSchedule.courseList(result2);
        }else {
            //从教务系统获取课程表
            Object obtainSchedule = HttpObtainSchedule.obtainSchedule(user,grade,semester);
            //System.out.println("obtainSchedule:"+obtainSchedule);
            if(obtainSchedule == (Object) 302){
                courseList = (List<Course>) HttpObtainSchedule.obtainSchedule(user,grade,semester);
            }else {
                courseList = (List<Course>) obtainSchedule;
            }
        }


        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("courseList",courseList);
        return ResponseUtil.ok(result);
    }

}
